package com.googlecode.garbagecan.perf4jstudy.spring2;

import java.io.Serializable;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Logger;
import org.perf4j.StopWatch;
import org.springframework.aop.support.AopUtils;

public final class MonitoringInterceptor implements MethodInterceptor, Serializable {

	private static final long serialVersionUID = 1L;

	private static Logger logger = Logger.getLogger("org.perf4j.TimingLogger");
	
	public Object invoke(MethodInvocation invocation) throws Throwable {
		String className = AopUtils.getTargetClass(invocation.getThis()).getName();
		String methodName = invocation.getMethod().getName();
		String name = className + "." + methodName;
		
		StopWatch stopWatch = new StopWatch(name);
		try {
			return invocation.proceed();
		} finally {
			stopWatch.stop();
			logger.info(stopWatch.toString());
		}
	}
}